package com.yyy.service;

import com.yyy.entity.Passenger;
import com.yyy.entity.TicketInfo;
import com.yyy.repository.PassengerRepository;
import com.yyy.repository.TicketInfoReposity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.krb5.internal.Ticket;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

@Service
public class TicketInfoService extends AbstractBaseService<TicketInfo, Integer, TicketInfoReposity> {

    @Resource
    private PassengerRepository passengerRepository;

    @PersistenceContext
    private EntityManager entityManager;

    public Page<TicketInfo> getTicketList(final Specification<TicketInfo> spec, final Pageable pageable) {
        return super.queryAll(spec, pageable);
    }

    public List<Passenger> findByNameLikeAndCardNum(String name, String cardNum) {
        return passengerRepository.findByNameLikeAndCardNum(name, cardNum);
    }

    public List<TicketInfo> createCriteriaQuery() {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<TicketInfo> criteriaQuery = criteriaBuilder.createQuery(TicketInfo.class);
        Root<TicketInfo> root = criteriaQuery.from(TicketInfo.class);
        List<Selection<?>> selections = new LinkedList<>();
        selections.add(root.get("segmentId"));
        selections.add(criteriaBuilder.count(root.get("count").as(Long.class)));

        List<Expression<?>> groupingList = new LinkedList<>();
        groupingList.add(root.get("segmentId"));
        criteriaQuery.multiselect(selections);
        criteriaQuery.groupBy(groupingList);
        return entityManager.createQuery(criteriaQuery).setFirstResult(0).setMaxResults(100).getResultList();
    }
}
